window.onerror = function myErrorHandler(errorMsg, url, lineNumber) {
        return true; // error is handled
    }

String.prototype.replaceAll = function(stringToFind,stringToReplace){
    var temp = this;
    var index = temp.indexOf(stringToFind);
        while(index != -1){
            temp = temp.replace(stringToFind,stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
    }

$(document).ready(function (){

	function showBackground(jObj,bgSrc){
		jObj.css('background-image', 'url('+bgSrc+')');
	}
	
	function preloadBackground(selector){
		if (!$.browser.webkit) return;
		$(selector).each(function(){
			var jObj = $(this);
			var bgSrc = $(this).css("background-image");
			bgSrc = bgSrc.substr(4,bgSrc.length-5);
			$(this).css("background-image", "none");
			$('<img/>').attr('src', bgSrc).load(function() {
				setTimeout(function(){ showBackground(jObj,bgSrc); },100);
			});
		});	
	}

	preloadBackground('body.home');
	preloadBackground('#slider');
	preloadBackground('#slider .slide:first .visual .ie7fix');

	
	$('img:not(.nofade)')
	.hide()
	.one("load",function () {
		if ( ($.browser.msie) && (browserVersion < 9)) {
			$(this).show();
		} else {
			// $(this).fadeIn("slow"); all images fadein at the same time, performance is slow
			var index = $('img').index(this);
			if (index < 7) {
				$(this).delay(330*index).fadeIn(300);
			} else {
				$(this).show(); // only fade the first 6 images to improve performance
			}
		}
	})
	.error(function () {
	  // notify the user that the image could not be loaded
	})
	.each(function(){
		if (this.complete) $(this).trigger('load');
	});


	$('#css-validator').attr('href','http://jigsaw.w3.org/css-validator/check?uri=referer&profile=css3');

	
	$('.social-links .google-plus').append('<g:plusone size="medium" annotation="inline" width="35"></g:plusone>');

	
	var bg = $('body');
	
	// Function index slides
	function indexSlide(curSlide){
		var i = 1;
		$('#slider .slide').removeClass('current').each(function(){
			$(this).attr('index',i);
			if (i==curSlide) {
				$(this).addClass('current');
			}
			i++;
		});
		return i-1;
	}

	var maxSlideIndex = indexSlide(2),
		slideWidth = $('#slider .slide').width()
		slideWrapperWidth = slideWidth*(maxSlideIndex+1);
	
	$('#slider .slides-wrapper').width(slideWrapperWidth);
	
	// Move the last slide to Top
		$('#slider .slide[index='+maxSlideIndex+']')
			.clone()
			.attr('index',0)
			.prependTo('#slider .slides-wrapper');
			
		$('#slider .slide[index='+maxSlideIndex+']').remove();
			
		indexSlide(2);
	
	
	var onMove = false,
		speed = 2000;
	
	function sliderMoveLeft() {
		
		// Prevent repeated keypress / click
		if (onMove) {
			return;
		} else {
			onMove = true;
		}
		
		bg.animate({
			"background-position-x": "+=120px"
		}, speed*2, "swing");
		
		// Clone the first slide to the right end
		$('#slider .slide.current')
			.prev()
			.clone()
			.attr('index',maxSlideIndex+1)
			.css({ width: slideWidth })
			.appendTo('#slider .slides-wrapper');
		
		$('#slider .slide.current')
			.find('.text')
			.hide()
			.parent()
			.next()
			.find('.text')
			.hide()
			.parent()
			.prev()
			.prev()
			.animate({ width: 0 }, speed, "easeInOutExpo", function(){
				$(this)
					.next().next().find('.text').fadeTo(speed/2,1,"easeInSine")
					.parent().prev().find('.text').show();
				$(this).remove();
				// Reindex all slides
				indexSlide(2);
				onMove = false;						
			});
		
	}
	
	function sliderMoveRight() {
		
		// Prevent repeated keypress / click
		if (onMove) {
			return;
		} else {
			onMove = true;
		}

		bg.animate({
			"background-position-x": "-=120px"
		}, speed*2, "swing");
		
		// Clone the last slide to the left
		$('#slider .slide[index='+maxSlideIndex+']')
			.clone()
			.attr('index',0)
			.css({ width: 0 })
			.prependTo('#slider .slides-wrapper');
		
		$('#slider .slide.current')
			.find('.text')
			.hide()
			.parent()
			.find('.visual')
			.fadeOut(speed/8)
			.parent()			
			.prev()
			.find('.text')
			.hide()
			.parent()
			.prev()
			.animate({ width: slideWidth }, speed, "easeOutExpo", function(){
				$(this)
					.next().find('.text').fadeTo(speed/2,1,"easeInSine").parent()
					.next().find('.text').show().parent().find('.visual').show();
				$('#slider .slide[index='+maxSlideIndex+']').remove();
				// Reindex all slides
				indexSlide(2);
				onMove = false;						
			});
		
	}
	
	var searchInputNotInFocus = true;

	// Keyboard event handler
	$(document).keydown(function (e) {
	
		if ($('body').hasClass('home') && (searchInputNotInFocus)) {

			switch (e.which) {
				case 39: // right
					e.preventDefault();
					if (sliderAutoPlay) {
						stopSlideAutoPlay();
					}
					sliderMoveLeft();
					break;
				case 37: // left
					e.preventDefault();
					if (sliderAutoPlay) {
						stopSlideAutoPlay();
					}
					sliderMoveRight();
					break;
			}
		}
	});
	
	// Hover effects for left and right controls
	var slideControlW = $('#slider .prev').width();
	$('#slider .prev')
		.add('#slider .next')
		.hover(function(){
			$(this).animate({ width: slideControlW-10 },speed/2,"easeOutSine");
			if ($(this).hasClass('next')) {
				$('#slider .prev').parent().fadeTo("fast",0.2);
			} else {
				$('#slider .next').parent().fadeTo("fast",0.2);
			}
		},function(){
			$(this).animate({ width: slideControlW },speed/3,"easeOutSine");
			if ($(this).hasClass('next')) {
				$('#slider .prev').parent().fadeTo("fast",1);
			} else {
				$('#slider .next').parent().fadeTo("fast",1);
			}
		}).click(function(){
			if ($(this).hasClass('next')) {
				sliderMoveLeft();
			} else if ($(this).hasClass('prev')) {
				sliderMoveRight();
			}
		});
	
	// AutoPlay for Slider
	var sliderTimer, sliderAutoPlay;
	var autoPlayCount = 0, autoPlayDir = "left";

	function slideMove(){
		//$('#wpstats').hide();
		if (autoPlayDir == "left") {
			sliderMoveLeft();
		} else {
			sliderMoveRight();
		}		
		autoPlayCount++;
		if (autoPlayCount == 3) {
			autoPlayCount = 0;
			autoPlayDir = (autoPlayDir=="left")? "right" : "left";
		}
	}
	
	var slideTimer;
	
	function startSlideAutoPlay(){
		sliderAutoPlay = true;
		slideMove();
		slideTimer = setInterval(function(){
			slideMove();
		}, speed*6);
	}

	function stopSlideAutoPlay(){
		sliderAutoPlay = false;
		if (typeof slideTimer !== 'undefined') {
			clearInterval(slideTimer);
		}
	}
	
	
	// Autoplay for home slider
	if ($('body').hasClass('home')) {
		setTimeout(function(){
			if (!sliderAutoPlay) {
				startSlideAutoPlay();
			}
		},2000);
	}
	
	var mouseEnter = false;
	
	$('.home #slider').add('.home #main-menu').add('.home .language').add('.home .box-1').mouseenter(function(){
		stopSlideAutoPlay();
		mouseEnter = true;
	}).mouseleave(function(){
		setTimeout(function(){
			if (!sliderAutoPlay && !mouseEnter) {
				startSlideAutoPlay();
			}
		},2000);
		mouseEnter = false;
	});
	
	$('.home .box-2').add('.home #footer').mouseenter(function(){
		stopSlideAutoPlay();
		$('*').stop(true,true);
		mouseEnter = true;
	}).mouseleave(function(){
		setTimeout(function(){
			if (!sliderAutoPlay && !mouseEnter) {
				startSlideAutoPlay();
			}
		},2000);
		mouseEnter = false;
	});
	
	// Hover effect for main menu
	var menuW = $('#main-menu').width(),
		wrapW = $('#main-menu-wrapper').outerWidth(),
		leftW = wrapW-menuW, menuInTimer, menuOutTimer, onHover = false;
	
	setTimeout(function(){ returnIndicator(); },500);
	
	$('#main-menu ul li')
		.hover(function(){
			clearTimeout(menuOutTimer);
			// stopSlideAutoPlay();
			jObj = $(this);
			if (onHover) {
				moveIndicator(jObj);
			} else {
				menuInTimer = setTimeout(function(){
								moveIndicator(jObj);
							},300);
			}
		}, function(){
			clearTimeout(menuInTimer);
			menuOutTimer = setTimeout(function(){
							returnIndicator();
							// startSlideAutoPlay();
						},150);
		})
		.click(function(){
			clicked = true;
			jObj = $(this);
			moveIndicatorFast(jObj);
			// $('#indicator .middle').hide();
		});

	function moveIndicator(jObj){
			if (jObj.length == 0) { return; }
			var newLeftW = leftW+jObj.position().left,
				newMiddW = jObj.width();
			$('#indicator .left')
				.stop().animate({ width: newLeftW },speed*2,"easeOutExpo");
			$('#indicator .middle')
				.stop().animate({ width: newMiddW },speed*2,"easeOutExpo");
			onHover = true;
	}
	
	function moveIndicatorFast(jObj){
			if (jObj.length == 0) { return; }
			var newLeftW = leftW+jObj.position().left,
				newMiddW = jObj.width();
			$('#indicator .left')
				.stop().animate({ width: newLeftW },200,"easeOutExpo");
			$('#indicator .middle')
				.stop().animate({ width: newMiddW },200,"easeOutExpo");
			onHover = true;
	}
	
	var clicked = false;
	
	function returnIndicator(){
		if (clicked) { return; }
		var newLeftW = 0,
			newMiddW = 0;
		if ($('#main-menu ul li.current').length == 0) {
			// return; 
		} else {
			newLeftW = leftW+$('#main-menu ul li.current').position().left,
			newMiddW = $('#main-menu ul li.current').width();
		}
		$('#indicator .left')
			.stop().animate({ width: newLeftW },speed,"easeOutExpo");
		$('#indicator .middle')
			.stop().animate({ width: newMiddW },speed,"easeOutExpo");
		onHover = false;
	}
	
	var numProjects = $('#portfolio .project').length,
		widProject = $('#portfolio .project').outerWidth(true)
		widWrapper = (numProjects+1)*widProject,
		projectMove = false;
		
	$('#portfolio .portfolio-wrapper').width(widWrapper);
	
	widProject = $('#portfolio .project').width();
	
	function prepareProjects(){
		var i = 1;
		$('#portfolio .project').each(function(){
		$(this)
			.removeClass('clone')
			.removeClass('first')
			.removeClass('last');
			if (i == 1) {
				$(this).addClass('first');
			} else if (i == numProjects) {
				$(this).addClass('last');
			}
			i++;
		});
		projectMove = false;
	}
	
	prepareProjects();

	// Move the last project to Top
		$('.home #portfolio .project.last')
			.clone()
			.removeClass('last')
			.prependTo('#portfolio .portfolio-wrapper');
			
		$('.home #portfolio .project.last').remove();
			
		prepareProjects();

		
	$('#portfolio .controls > div')
		.bind("click", function(){
				
			if (projectMove) { return; }

			if ($(this).find('div').hasClass('prev')) {

				// Clone the first project to the right
				// Animate its width to zero and remove it
				
				$('#portfolio .project.first')
					.clone().removeClass('first')
					.appendTo('#portfolio .portfolio-wrapper');
				
				$('#portfolio .project.first')
					.animate({ width: 0, marginRight: 0 },300,"easeInSine", function(){
						$(this).remove();
						prepareProjects();
					});
			} else if ($(this).find('div').hasClass('next')) {

				// Clone the last project to the left
				// Animate its width to zero and remove it
				
				$('#portfolio .project.last')
					.clone().removeClass('last')
					.addClass('clone').css({ width: 0, paddingRight: 0, paddingLeft: 0 })
					.prependTo('#portfolio .portfolio-wrapper');
				
				$('#portfolio .project.clone')
					.animate({ width: widProject, paddingRight: 12, paddingLeft: 13 },300,"easeOutSine", function(){
						$('#portfolio .project.last').remove();
						prepareProjects();
					});
			}
		}).hover(function(){
			if ($(this).find('div').hasClass('prev')) {
				$('#portfolio .controls .next').parent().fadeTo("fast", 0.3);
			} else if ($(this).find('div').hasClass('next')) {
				$('#portfolio .controls .prev').parent().fadeTo("fast", 0.3);
			}
		},function(){
			if ($(this).find('div').hasClass('prev')) {
				$('#portfolio .controls .next').parent().fadeTo("fast", 1);
			} else if ($(this).find('div').hasClass('next')) {
				$('#portfolio .controls .prev').parent().fadeTo("fast", 1);
			}
		});
		
	function showProjectInfo(jObj){
		jObj.find('.info')
			.animate({ height: 62, paddingTop: 10, paddingBottom: 10 }, 150, "easeInSine");
	}
	
	var timer_1;
	
	$('#portfolio .project .thumb a')
		.live("mouseenter",function(){
			var jObj = $(this);
			timer_1 = setTimeout(function(){
				showProjectInfo(jObj);
			}, 150);
		}).live("mouseleave",function(){
			$(this).find('.info')
				.animate({ height: 0, paddingTop: 0, paddingBottom: 0 }, 150, "easeOutSine");
			clearTimeout(timer_1);
		});
		
	var k = $('#search input.text').val();
	$('#search input.text').focus(function(){
		searchInputNotInFocus = false;
		if ($(this).val() == 'Enter search terms') $(this).val('');
	}).blur(function(){
		searchInputNotInFocus = true;
		if ($.trim($(this).val()) == '') $(this).val(k);
	});
	
	$('#submitButton').click(function(){
		$('#search').submit();
	});
	
	if ( ($.browser.opera) && (browserVersion < 11)) {
		// do not use fade effects
		var disable_fadeLinks = true;
	} else {
		$('.box-1 .button.css')
			.add('.box-2 .button.css')
			.add('#footer .links.css')
			.add('#top-bar-wrapper .top-bar.css')
			.add('.sidebar .blog-post.css')
			.add('#sub-menu.css')
			.add('.more-button.css')
				.removeClass('css');
	}
	
	
	$('.box-1 .button a')
		.add('.box-2 .button a')
		.add('#footer .links ul li a')
		.add('#top-bar-wrapper .top-bar a')
		.add('.sidebar .blog-post .title h4 a')
		.add('#sub-menu a')
		.add('.more-button a')
			.each(function(){
				if (disable_fadeLinks) {
					return;
				}
				var a = $(this);
				// Create the span for the fade effect
				a.append('<span class="hover">' + a.html() + '</span>');
				a.find('span.hover').hide();
			}).hover(function() {
					$(this).find("span.hover").stop(true,true).fadeIn("slow");
			}, function() {
					$(this).find("span.hover").stop(true,true).fadeOut("normal");
			});

	/*if ( ($.browser.msie) ) {
		$('.page #main .content').addClass('css');
		$('.page #main .content p a span').remove();
	}*/

			
	$('.box-1').add('.box-2')
		.css('box-shadow','0px 0px 3px 2px rgba(155,155,155,.1)')
		.css('-webkit-box-shadow','0px 0px 3px 2px rgba(155,155,155,.1)')
		.css('-moz-box-shadow','0px 0px 3px 2px rgba(155,155,155,.1)');
		

	
	// Fix for IE9
	if ( ($.browser.msie) && (browserVersion <= 9)) {
		$('.one-half img').show();
		$('#sub-menu li.active ul').show();
	} else {
		$('#sub-menu li.active ul').slideDown("normal","easeInOutExpo");
	}
	
	if ($("#mcs2_container").length > 0) {
		$("#mcs2_container").mCustomScrollbar("vertical",600,"easeOutCirc",0,"fixed","yes","no",0);
	}
	
	$('a').focus(function(){
		$(this).blur();
	});
	
	
	// Remember to add round corners for IE7-8
	
	
	$('#sub-menu > ul > li > a').click(function(e){
		if ($(this).hasClass('default')) { return; }

		rel = $(this).attr('rel');
		
		if ($('#'+rel).length == 0) { return; }
		
		$('.services').not('#'+rel).removeClass('expanded').slideUp("normal","easeInOutExpo");
		$('a.toggle[rel="'+rel+'"]').toggle();
		$('#'+rel).slideToggle("normal","easeInOutExpo", function(){
			$(this).toggleClass('expanded');
			checkExpanded();
		});

		e.preventDefault();
		if ($(this).parent().hasClass('active')) {
			if ( ($.browser.msie) && (browserVersion <= 9)) {
				$(this).parent().find('ul').toggle("normal","easeInOutExpo");
			} else {
				$(this).parent().find('ul').slideToggle("normal","easeInOutExpo");
			}
		} else {
			var jObj = $(this).parent();
			if ($('#sub-menu li.active').length > 0) {
				$('#sub-menu li.active')
						.removeClass('active')
							.find('ul').slideUp("normal","easeInOutExpo",function(){
								if ( ($.browser.msie) && (browserVersion <= 9)) {
									jObj.addClass('active').find('ul').toggle("normal","easeInOutExpo");
								} else {
									jObj.addClass('active').find('ul').slideDown("normal","easeInOutExpo");
								}
							});
			} else {
				if ( ($.browser.msie) && (browserVersion <= 9)) {
					jObj.addClass('active').find('ul').toggle("normal","easeInOutExpo");
				} else {
					jObj.addClass('active').find('ul').slideDown("normal","easeInOutExpo");
				}
			}
		}
		
	});
	
	$('.tweets li a').each(function(){
		var attr = $(this).attr('target');
		if (!attr) {
			$(this).attr('target','_blank');
		}
	});
	
	var aObj,rel;

	$('a.toggle').click(function(e){
		e.preventDefault();
		// $(this).find('span:first-child').toggleClass('arrow').toggleClass('arrow-top');
		rel = $(this).attr('rel');
		$('.services').not('#'+rel).removeClass('expanded').slideUp("fast");
		$('#'+rel).toggleClass('expanded').slideToggle("slow","easeInOutExpo");
		checkExpanded();
		if ($('a.service-heading[rel="'+rel+'"]').length > 0) {
			var top = $('a.service-heading[rel="'+rel+'"]').offset().top;
			$('html, body').stop().animate({
					scrollTop: top
				}, {
					duration: 1000,
					easing: "swing",
					complete: function() {

						$('#sub-menu > ul > li.active')
							.removeClass('active')
							.find('ul')
							.hide();

						$('#sub-menu > ul > li > a[rel="'+rel+'"]')
							.parent()
							.addClass('active')
							.find('ul')
							.show();


					}
				  });
		}
		/*aObj = $(this);
		var wait = setInterval(function() {
		if( !aObj.find('span:last-child').is(":animated") ) {
				clearInterval(wait);
				var h = aObj.html();
				var t = aObj.find('span:last-child').text();
				if (t=='Show details') {
					var r = 'Hide details';
				} else {
					var r = 'Show details';
				}
				h = h.replaceAll(t,r);
				aObj.html(h);
			}
		}, 200);*/
	});
	
	function checkExpanded(){
		$('a.toggle').each(function(){
			var rel = $(this).attr('rel');
			if ($('#'+rel).hasClass('expanded')) {
				$(this).find('.hover').andSelf().hide();
			} else {
				$(this).show();
				$('#'+rel).hide();
			}
		});
	}
	
	checkExpanded();
	
	$('a.go-top').click(function(e){
		e.preventDefault();
		$('html, body').stop().animate({
					scrollTop: 0
				}, {
					duration: 1000,
					easing: "easeInOutExpo"
					});
	});
	
	$('.relevanssi-query-term').each(function(){
		var text = $(this).text();
		if ((text.length <= 1) || (text.indexOf(' ') > -1)) {
			$(this).removeClass('relevanssi-query-term');
		}
	});
	
	$('#comments').each(function(){
		var text = $.trim($(this).text());
		if (text.length == 0) {
			$(this).remove();
		}
		
	});
	
	//$('#wpstats').hide();
	
	$(".rater ul").each(function(){
		var postID = $(this).attr("id");
		postID = postID.substr(5,postID.length-5);
		$(this).attr("data-post",postID);
	});
	
	var fancyBoxBgImg;
	
	$("a.iframe").fancybox({
		'centerOnScroll'	: true,
		'overlayOpacity'	: 0.6,
		'overlayColor'		: '#000',
		'width'				: 1080,
		'height'			: 640,
		'onStart'		: function(){
			$("html").css("overflow-y","hidden");
		},		'onComplete'		: function(){
			fancyBoxBgImg = $("#fancybox-content").css("background-image");
			$("#fancybox-content").css("background-image","none");
		},
		'onClosed'		: function(){
			$("#fancybox-content").css("background-image",fancyBoxBgImg);
			$("html").css("overflow-y","auto");
		}
	});
	
});